package com.pig4cloud.pig.village.file.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.pig4cloud.common.minio.service.MinioTemplate;
import com.pig4cloud.pig.common.core.constant.CommonConstants;
import com.pig4cloud.pig.village.file.service.IFileService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @author limbray.li
 * @date 2021/7/12
 */
@Service
@Slf4j
public class FileServiceImpl implements IFileService {
	@Resource
	private MinioTemplate minioTemplate;

	/**
	 * 上传文件
	 *
	 * @param file
	 * @return
	 */
	@Override
	public String uploadFile(MultipartFile file) {
		String fileName = IdUtil.simpleUUID() + StrUtil.DOT + FileUtil.extName(file.getOriginalFilename());
		Map<String, String> resultMap = new HashMap<>(4);
		resultMap.put("fileName", fileName);
		try {
			minioTemplate.putObject(CommonConstants.BUCKET_NAME, fileName, file.getInputStream());
		} catch (Exception e) {
			log.error("上传失败", e);
			return "上传失败";
		}
		return fileName;
	}

	/**
	 * 读取文件
	 *
	 * @param fileName
	 * @param response
	 */
	@Override
	public void getFile(String objectName,String fileName, HttpServletResponse response) {
		try (InputStream inputStream = minioTemplate.getObject(CommonConstants.BUCKET_NAME,
				objectName)) {
			response.setContentType("application/octet-stream; charset=UTF-8");
			response.setHeader("Content-Disposition", "attachment;fileName="+fileName);
			IoUtil.copy(inputStream, response.getOutputStream());
		} catch (Exception e) {
			log.error("文件读取异常", e);
		}
	}


	/**
	 * 删除文件
	 *
	 * @param fileName
	 * @return
	 */
	@Override
	@SneakyThrows
	@Transactional(rollbackFor = Exception.class)
	public Boolean deleteFile(String fileName) {
		minioTemplate.removeObject(CommonConstants.BUCKET_NAME, fileName);
		return true;
	}

}
